<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>WebSocket 连接测试</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            max-width: 800px;
            margin: 0 auto;
            padding: 20px;
        }
        .container {
            border: 1px solid #ccc;
            border-radius: 5px;
            padding: 20px;
            margin-bottom: 20px;
        }
        .form-group {
            margin-bottom: 15px;
        }
        label {
            display: block;
            margin-bottom: 5px;
            font-weight: bold;
        }
        input[type="text"] {
            width: 100%;
            padding: 8px;
            border: 1px solid #ccc;
            border-radius: 4px;
        }
        button {
            background-color: #4CAF50;
            color: white;
            padding: 10px 15px;
            border: none;
            border-radius: 4px;
            cursor: pointer;
        }
        button:hover {
            background-color: #45a049;
        }
        .log-container {
            background-color: #f8f8f8;
            padding: 10px;
            border-radius: 4px;
            max-height: 300px;
            overflow-y: auto;
            font-family: monospace;
            white-space: pre-wrap;
        }
        .success {
            color: green;
        }
        .error {
            color: red;
        }
        .info {
            color: blue;
        }
    </style>
</head>
<body>
    <h1>WebSocket 连接测试工具</h1>
    
    <div class="container">
        <div class="form-group">
            <label for="ws-url">WebSocket URL:</label>
            <input type="text" id="ws-url" value="ws://localhost:8080/api/websocket/1/0" placeholder="例如: ws://example.com/socket">
        </div>
            <div class="form-group">
            <button id="connect-btn">连接</button>
            <button id="disconnect-btn" disabled>断开</button>
            <button id="send-btn" disabled>发送消息</button>
            <button id="test-multiple-btn">批量测试</button>
            </div>
        </div>
        
    <div class="container">
        <h3>连接状态</h3>
        <div id="status">未连接</div>
        </div>
        
    <div class="container">
        <h3>日志</h3>
        <div class="log-container" id="log"></div>
    </div>

    <script>
        document.addEventListener('DOMContentLoaded', function() {
            const connectBtn = document.getElementById('connect-btn');
            const disconnectBtn = document.getElementById('disconnect-btn');
            const sendBtn = document.getElementById('send-btn');
            const testMultipleBtn = document.getElementById('test-multiple-btn');
            const urlInput = document.getElementById('ws-url');
            const statusEl = document.getElementById('status');
            const logEl = document.getElementById('log');
            
            let socket = null;
            
            // 日志函数
            const logger = {
                log: function(message) {
                    const logEntry = document.createElement('div');
                    logEntry.textContent = `[${new Date().toLocaleTimeString()}] ${message}`;
                    logEl.appendChild(logEntry);
                    logEl.scrollTop = logEl.scrollHeight;
                },
                error: function(message) {
                    const logEntry = document.createElement('div');
                    logEntry.textContent = `[${new Date().toLocaleTimeString()}] ${message}`;
                    logEntry.className = 'error';
                    logEl.appendChild(logEntry);
                    logEl.scrollTop = logEl.scrollHeight;
                },
                success: function(message) {
                    const logEntry = document.createElement('div');
                    logEntry.textContent = `[${new Date().toLocaleTimeString()}] ${message}`;
                    logEntry.className = 'success';
                    logEl.appendChild(logEntry);
                    logEl.scrollTop = logEl.scrollHeight;
                },
                info: function(message) {
                    const logEntry = document.createElement('div');
                    logEntry.textContent = `[${new Date().toLocaleTimeString()}] ${message}`;
                    logEntry.className = 'info';
                    logEl.appendChild(logEntry);
                    logEl.scrollTop = logEl.scrollHeight;
                }
            };
            
            // WebSocket 连接状态描述
            function getReadyStateDescription(readyState) {
                switch(readyState) {
                    case WebSocket.CONNECTING: return 'CONNECTING (0) - 连接中';
                    case WebSocket.OPEN: return 'OPEN (1) - 已连接';
                    case WebSocket.CLOSING: return 'CLOSING (2) - 关闭中';
                    case WebSocket.CLOSED: return 'CLOSED (3) - 已关闭';
                    default: return `UNKNOWN (${readyState})`;
                }
            }
            
            // WebSocket 关闭代码说明
            const closeCodeExplanations = {
                1000: '正常关闭',
                1001: '终端离开 (页面关闭)',
                1002: '协议错误',
                1003: '不支持的数据类型',
                1005: '没有收到预期的关闭状态码',
                1006: '异常关闭 (没有收到关闭帧)',
                1007: '数据格式不一致 (非UTF-8数据)',
                1008: '策略违规 (消息不符合规则)',
                1009: '消息太大',
                1010: '客户端期望服务器协商的扩展',
                1011: '服务器内部错误',
                1012: '服务重启',
                1013: '暂时性服务过载',
                1015: 'TLS握手失败'
            };
            
            // 连接按钮事件
            connectBtn.addEventListener('click', function() {
                const url = urlInput.value.trim();
                if (!url) {
                    logger.error('请输入有效的WebSocket URL');
                    return;
                }
                
                logger.log(`尝试连接到: ${url}`);
                
                try {
                    // 创建WebSocket连接
                    socket = new WebSocket(url);
                    
                    // 连接打开事件
                    socket.onopen = function() {
                        logger.success(`连接成功: ${url}`);
                        statusEl.textContent = 'Connected';
                        statusEl.className = 'success';
                        connectBtn.disabled = true;
                        disconnectBtn.disabled = false;
                        sendBtn.disabled = false;
                    };
                    
                    // 收到消息事件
                    socket.onmessage = function(event) {
                        logger.info(`收到消息: ${event.data}`);
                    };
                    
                    // 发生错误事件
                    socket.onerror = function(event) {
                        logger.error(`连接错误`);
                        logger.error(`状态: ${getReadyStateDescription(socket.readyState)}`);
                        statusEl.textContent = 'Error';
                        statusEl.className = 'error';
                    };
                    
                    // 连接关闭事件
                    socket.onclose = function(event) {
                        const explanation = closeCodeExplanations[event.code] || '未知状态码';
                        logger.log(`连接关闭: 状态码 ${event.code} (${explanation})`);
                        
                        if (event.reason) {
                            logger.log(`关闭原因: ${event.reason}`);
                        }
                        
                        if (event.wasClean) {
                            logger.info('连接已正常关闭');
                        } else {
                            logger.error('连接异常关闭');
                        }
                        
                        statusEl.textContent = 'Disconnected';
                        statusEl.className = '';
                        connectBtn.disabled = false;
                        disconnectBtn.disabled = true;
                        sendBtn.disabled = true;
                        socket = null;
                    };
                } catch (error) {
                    logger.error(`创建连接失败: ${error.message}`);
                    statusEl.textContent = 'Error';
                    statusEl.className = 'error';
                }
            });
            
            // 断开连接按钮事件
            disconnectBtn.addEventListener('click', function() {
                if (socket) {
                    logger.log('正在关闭连接...');
                    socket.close(1000, "手动关闭");
                }
            });
            
            // 发送消息按钮事件
            sendBtn.addEventListener('click', function() {
                if (socket && socket.readyState === WebSocket.OPEN) {
                    const message = prompt('请输入要发送的消息:', 'PING');
                    if (message) {
                        logger.log(`发送消息: ${message}`);
                        socket.send(message);
                    }
                } else {
                    logger.error('WebSocket未连接，无法发送消息');
                }
            });
            
            // 批量测试按钮事件
            testMultipleBtn.addEventListener('click', function() {
                const baseUrls = [
                    'ws://47.109.146.201:6401',
                    'ws://47.109.146.201:6100',
                    'ws://47.109.146.201:8080',
                    'wss://47.109.146.201:6401',
                    'ws://localhost:8080'
                ];
                
                const paths = [
                    '/websocket/1/0',
                    '/api/websocket/1/0',
                    '/1/0'
                ];
                
                logger.log('开始批量测试多个WebSocket端点...');
                
                // 清除之前的连接
                if (socket) {
                    socket.close();
                    socket = null;
                }
                
                let testIndex = 0;
                const totalTests = baseUrls.length * paths.length;
                
                function testNextEndpoint() {
                    if (testIndex >= totalTests) {
                        logger.log('所有测试完成');
                        return;
                    }
                    
                    const baseUrlIndex = Math.floor(testIndex / paths.length);
                    const pathIndex = testIndex % paths.length;
                    
                    const baseUrl = baseUrls[baseUrlIndex];
                    const path = paths[pathIndex];
                    const fullUrl = `${baseUrl}${path}`;
                    
                    logger.log(`测试 ${testIndex + 1}/${totalTests}: ${fullUrl}`);
                    
                    testIndex++;
                    
                    try {
                        const testSocket = new WebSocket(fullUrl);
                        
                        testSocket.onopen = function() {
                            logger.success(`✓ 连接成功: ${fullUrl}`);
                            // 连接成功后主动关闭
                            setTimeout(() => {
                                testSocket.close(1000, "测试完成");
                            }, 1000);
                        };
                        
                        testSocket.onmessage = function(event) {
                            logger.info(`收到消息: ${event.data}`);
                        };
                        
                        testSocket.onerror = function() {
                            logger.error(`✗ 连接失败: ${fullUrl}`);
                        };
                        
                        testSocket.onclose = function() {
                            // 测试下一个端点
                            setTimeout(testNextEndpoint, 1000);
                        };
                    } catch (error) {
                        logger.error(`创建连接失败: ${error.message}`);
                        // 测试下一个端点
                        setTimeout(testNextEndpoint, 1000);
                    }
                }
                
                // 开始测试第一个端点
                testNextEndpoint();
            });
        });
    </script>
</body>
</html> 